package org.wavetech.adapter;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.RecyclerView;

import org.wavetech.adapter.HeaderViewOwner;

public class HeaderModule implements HeaderViewOwner {

    private final Context context;
    private RecyclerView.Adapter<?> adapter;
    private LinearLayout containerView;

    public HeaderModule(Context context, RecyclerView.Adapter<?> adapter) {
        this.context = context;
        this.adapter = adapter;
    }

    public LinearLayout getContainerView() {
        ensureContainerExists();
        return containerView;
    }

    private void ensureContainerExists() {
        if (containerView == null) {
            containerView = new LinearLayout(context);
            containerView.setOrientation(LinearLayout.VERTICAL);
        }
    }

    public boolean hasHeaderView() {
        return containerView != null && containerView.getChildCount() > 0;
    }

    @Override
    public void addHeaderView(View view) {
        ensureContainerExists();
        boolean hasHeaderView = hasHeaderView();
        containerView.addView(view);
        if (!hasHeaderView) {
            adapter.notifyItemInserted(0);
        }
    }

    @Override
    public void removeHeaderView(View view) {
        if (!hasHeaderView()) return;
        int index = containerView.indexOfChild(view);
        if (index < 0) return;
        containerView.removeView(view);
        if (!hasHeaderView()) {
            adapter.notifyItemRemoved(0);
        }
    }

    @Override
    public void removeHeaderView(int position) {
        if (!hasHeaderView()) return;
        if (position > containerView.getChildCount() - 1) return;
        containerView.removeViewAt(position);
        if (!hasHeaderView()) {
            adapter.notifyItemRemoved(0);
        }
    }


}
